﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Castle.DynamicProxy;

namespace Sharp.Infrastructure.WebApiClient
{
    /// <summary>
    /// api客户端代理
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class WebApiClientServiceProxy<T> : IDisposable where T : class
    {
        private ProxyGenerator Generator = new ProxyGenerator();
        private IHttpClient _httpClient;
        public List<IActionFilter> Filters;

        /// <summary>
        /// api客户端代理
        /// </summary>
        /// <param name="httpMessageHandler"></param>
        public WebApiClientServiceProxy(HttpMessageHandler httpMessageHandler = null)
        {


        }

        private T CreateClient()
        {
            if (WebApiServices.TryGetValue(typeof(T), out var hac))
            {
                IActionFilter[] filters = hac.ActionFilters ?? new IActionFilter[] { };
                if (Filters == null)
                {
                    Filters = filters.ToList();
                }
                else
                {
                    Filters.AddRange(filters);
                }
                _httpClient = new HttpClientAdapter(new HttpClient());

                return Generator.CreateInterfaceProxyWithoutTarget<T>(
                    new WebClientRequestInterceptor<T>(hac.HttpHost, _httpClient, Filters.ToArray()));
            }

            throw new WebApiClientException("没有配置接口的Url。");
        }
        /// <summary>
        /// 模拟Wcf的Channel
        /// </summary>
        public T Channel => CreateClient();

        public void Dispose()
        {

        }
    }
}